
package com.joysuch.wwyt.mh.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.api.mh.rest.MhMonitPointRestSender;
import com.joysuch.wwyt.api.mh.socket.MhMonitPointSocketSender;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityCollection;
import com.joysuch.wwyt.bp.entity.BpProductionFacility;
import com.joysuch.wwyt.bp.enums.DeviceFacilityLifecycles;
import com.joysuch.wwyt.bp.enums.ProductionFacilityStates;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityCollectionService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.*;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.security.ShiroUser;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.bean.*;
import com.joysuch.wwyt.mh.dto.MhGradingAlarmDto;
import com.joysuch.wwyt.mh.entity.*;
import com.joysuch.wwyt.mh.entity.dsl.QMhAlarmMessage;
import com.joysuch.wwyt.mh.enums.AlarmRecordStateEnum;
import com.joysuch.wwyt.mh.enums.PeriodUnitEnum;
import com.joysuch.wwyt.mh.mapper.MhGradingAlarmMapper;
import com.joysuch.wwyt.mh.repository.*;
import com.joysuch.wwyt.mh.service.*;
import com.joysuch.wwyt.mh.storage.MonitorPointData;
import com.joysuch.wwyt.mh.storage.impl.AbstractBizIMonitorPointDataHandler;
import com.joysuch.wwyt.mh.websocket.MonitorPointDataWebSocket;
import com.joysuch.wwyt.mh.websocket.WebsocketDataType;
import com.joysuch.wwyt.monitoringcenter.service.MonitoringCenterService;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.entity.RiskDynamicConfig;
import com.joysuch.wwyt.risk.entity.RiskDynamicRecord;
import com.joysuch.wwyt.risk.entity.RiskEvaluationControl;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.repository.RiskDynamicConfigDao;
import com.joysuch.wwyt.risk.repository.RiskEvaluationControlDao;
import com.joysuch.wwyt.risk.service.RiskDynamicRecordService;
import com.joysuch.wwyt.risk.service.RiskEvaluationBusinessService;
import com.joysuch.wwyt.util.RegionUtil;
import com.joysuch.wwyt.workflow.service.WorkFlowTaskDynamicService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service("MhAlarmMessageServiceImpl")
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MhAlarmMessageServiceImpl extends AbstractBizIMonitorPointDataHandler implements MhAlarmMessageService {

    @Resource
    private final JPAQueryFactory jqf;
    @Resource
    private final MhAlarmMessageDao messageDao;
    @Resource
    private final MhMonitoringPointDao monitoringPointDao;
    @Resource
    private final MhMonitoringPointServiceImpl mhMonitoringPointService;
    @Resource
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Resource
    private BpDeviceFacilityCollectionService bpDeviceFacilityCollectionService;
    @Resource
    private MhMajorHazardDao mhMajorHazardDao;
    @Resource
    private BpProductionFacilityDao bpProductionFacilityDao;
    @Autowired
    private MhMonitoringTypeDao mhMonitoringTypeDao;
    @Autowired
    private MonitorPointDataWebSocketService monitorPointDataWebSocketService;
    @Autowired
    private MhAlarmSettingDao mhAlarmSettingDao;
    @Autowired
    private BpDeviceFacilityMonitoringPointDao bpDeviceFacilityMonitoringPointDao;
    @Autowired
    private BpDeviceFacilityRepairRecordDao bpDeviceFacilityRepairRecordDao;
    @Autowired
    private BpDeviceFacilityMaintainRecordDao bpDeviceFacilityMaintainRecordDao;
    @Autowired
    private BpDeviceFacilityCollectionDao bpDeviceFacilityCollectionDao;

    @Resource
    private MhMonitPointSocketSender mhMonitPointSocketMessageSender;
    @Resource
    private MhMonitPointRestSender mhMonitPointRestSender;
    @Autowired
    private MhMonitoringRealTimeService mhMonitoringRealTimeService;
    @Autowired
    private CustomAlarmMessageService customAlarmMessageService;
    @Autowired
    private BaseConfigService baseConfigService;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private RiskDynamicConfigDao riskDynamicConfigDao;
    @Autowired
    private RiskDynamicRecordService riskDynamicRecordService;
    @Autowired
    private RiskEvaluationBusinessService riskEvaluationBusinessService;
    @Autowired
    private RiskEvaluationControlDao riskEvaluationControlDao;
    @Autowired
    private WorkFlowTaskDynamicService workFlowTaskDynamicService;
    @Autowired
    private MhGradingAlarmService mhGradingAlarmService;

    @Resource
    private MhAlarmRecordService mhAlarmRecordService;

    @Resource
    private MhAlarmLimitConfigService mhAlarmLimitConfigService;

    @Autowired
    private BaseUserDao baseUserDao;

    @Autowired
    private MhGradingAlarmMapper mhGradingAlarmMapper;

//    @Value("${mh.monitPoint.api.socket.open}")
//    private boolean isSocket;
//    @Value("${mh.monitPoint.api.rest.open}")
//    private boolean isRest;

    private static final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3, r -> {
        Thread thread = new Thread(r, "alarm-message worker");
        thread.setDaemon(true);
        return thread;
    });

    @Override
    public Page<MhAlarmMessageListBean> getByPage(Pageable pageable, String detail, Long alarmTypeId, Integer level,
                                                  Integer state) {
        QMhAlarmMessage msg = QMhAlarmMessage.mhAlarmMessage;
        Predicate predicate = msg.isNotNull();
        // 执行动态条件拼装
        predicate = detail == null ? predicate : ExpressionUtils.and(predicate, msg.detail.like("%" + detail + "%"));
        predicate = level == null ? predicate : ExpressionUtils.and(predicate, msg.level.eq(level));
        predicate = state == null ? predicate : ExpressionUtils.and(predicate, msg.state.eq(state));
        predicate = alarmTypeId == null ? predicate
                : ExpressionUtils.and(predicate, msg.mhMonitoringType.id.eq(alarmTypeId));

        pageable = PageDataUtils.addOrderByDesc(pageable, "id");
        Page<MhAlarmMessage> all = messageDao.findAll(predicate, pageable);
        List<MhAlarmMessageListBean> list = new ArrayList<>();
        if (all.getTotalElements() > 0) {
            for (MhAlarmMessage m : all.getContent()) {
                MhAlarmMessageListBean mhAlarmMessageListBean = new MhAlarmMessageListBean();
                mhAlarmMessageListBean.setId(m.getId());
                mhAlarmMessageListBean.setCode(m.getCode());
                mhAlarmMessageListBean.setAlarmLevel(m.getLevel());
                mhAlarmMessageListBean.setAlarmLevelName(levelName(m));
                mhAlarmMessageListBean.setContent(m.getDetail());
                mhAlarmMessageListBean.setAlarmTime(m.getAlarmTime());
                mhAlarmMessageListBean.setMinitoringPointName(m.getMhMonitoringPoint().getName());
                mhAlarmMessageListBean.setMinitoringPointId(m.getMhMonitoringPoint().getId());
                mhAlarmMessageListBean.setMinitoringTypeId(m.getMhMonitoringType().getId());
                mhAlarmMessageListBean.setMinitoringTypeName(m.getMhMonitoringType().getName());
                mhAlarmMessageListBean.setState(m.getState());
                mhAlarmMessageListBean.setAlarmPosition(m.getAlarmPosition());
                mhAlarmMessageListBean.setStateName(stateName(m));
                mhAlarmMessageListBean.setRemark(m.getRemark());
                if (m.getMajorHazardFlag() != null && m.getMajorHazardFlag() == 1) {
                    mhAlarmMessageListBean.setMajorHazardFlagName("是");
                } else {
                    mhAlarmMessageListBean.setMajorHazardFlagName("否");
                }
                list.add(mhAlarmMessageListBean);
            }
        }
        return new PageImpl<>(list, pageable, all.getTotalElements());
    }

    private String stateName(MhAlarmMessage m) {
        String name = "";
        if (m.getState() != null) {
            if (m.getState() == 0) {
                name = "未处理";
            } else if (m.getState() == 1) {
                name = "已处理";
            }
        }
        return name;
    }

    private String levelName(MhAlarmMessage m) {
        String name = "";
        if (m.getLevel() != null) {
            if (m.getLevel() == 1 || m.getLevel() == 2) {
                name = "一级报警";
            } else {
                name = "二级报警";
            }
        }
        return name;
    }

    @Override
    public MhAlarmMessageListBean getById(Long id) {
        QMhAlarmMessage msg = QMhAlarmMessage.mhAlarmMessage;
        Predicate predicate = msg.isNotNull();
        predicate = id == null ? predicate : ExpressionUtils.and(predicate, msg.id.eq(id));
        Iterable<MhAlarmMessage> all = messageDao.findAll(predicate);
        if (all != null && !"".equals(all)) {
            for (MhAlarmMessage m : all) {
                MhAlarmMessageListBean mhAlarmMessageListBean = new MhAlarmMessageListBean();
                mhAlarmMessageListBean.setMinitoringTypeName(m.getMhMonitoringType().getName());
                mhAlarmMessageListBean.setMinitoringTypeId(m.getMhMonitoringType().getId());
                mhAlarmMessageListBean.setMinitoringPointId(m.getMhMonitoringPoint().getId());
                mhAlarmMessageListBean.setUnit(m.getMhMonitoringPoint().getUnit());
                mhAlarmMessageListBean.setMinitoringPointName(m.getMhMonitoringPoint().getName());
                mhAlarmMessageListBean.setContent(m.getDetail());
                mhAlarmMessageListBean.setAlarmLevel(m.getLevel());
                mhAlarmMessageListBean.setId(m.getId());
                mhAlarmMessageListBean.setAlarmTime(m.getAlarmTime());
                mhAlarmMessageListBean.setAlarmArea(m.getAlarmArea());
                mhAlarmMessageListBean.setAlarmDept(m.getAlarmDept());
                mhAlarmMessageListBean.setCode(m.getOrgCode());
                mhAlarmMessageListBean.setAlarmPosition(m.getAlarmPosition());
                mhAlarmMessageListBean.setCreateBy(m.getCreateBy());
                mhAlarmMessageListBean.setCreateTime(m.getCreateTime());
                mhAlarmMessageListBean.setDeleteFlag(m.getDeleteFlag());
                mhAlarmMessageListBean.setDeptCharger(m.getDeptCharger());
                mhAlarmMessageListBean.setHandleBy(m.getHandleBy());
                mhAlarmMessageListBean.setHandleTime(m.getHandleTime());
                mhAlarmMessageListBean.setMajorHazardFlag(m.getMajorHazardFlag());
                mhAlarmMessageListBean.setMajorHazardName(m.getMajorHazardName());
                mhAlarmMessageListBean.setState(m.getState());
                mhAlarmMessageListBean.setUpdateBy(m.getUpdateBy());
                mhAlarmMessageListBean.setUpdateTime(m.getUpdateTime());
                return mhAlarmMessageListBean;
            }
        }
        return null;
    }

    @Override
    public void save(Long id) {
        MhAlarmMessage one = messageDao.getOne(id);
        // one.setHandleBy(bizCodeGeneratorFacade.);
        one.setState(2);
        ShiroUser currentUser = Context.getCurrentUser();
        one.setHandleBy(currentUser == null ? null : currentUser.getUsername());
        one.setHandleTime(LocalDateTime.now());
        messageDao.save(one);
    }

    @Override
    public ResultBean harzardQuery(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null || endTime == null) {
            return ResultBean.fail(101, "开始时间/结束时间不能为空");
        }
        List<MhAlarmMessage> all = messageDao.findAllByAlarmTimeBetween(startTime, endTime);
        Map<LocalDateTime, List<MhAlarmMessage>> map = all.stream().collect(Collectors.groupingBy(r -> {
            LocalDateTime alarmTime = r.getAlarmTime();
            int second = alarmTime.getSecond();
            LocalDateTime localDateTime = alarmTime.minusSeconds(second);
            return localDateTime;
        }));
        List<AlarmEchartDto> dtoList = Lists.newArrayList();
        for (Map.Entry<LocalDateTime, List<MhAlarmMessage>> entry : map.entrySet()) {
            List<MhAlarmMessage> value = entry.getValue();
            // 1,2属于一级报警，其余二级
            int totalSize = value.size();
            Long oneLevel = value.stream().filter(r -> {
                Integer level = r.getLevel();
                if (level != null && (level == 1 || level == 2)) {
                    return true;
                }
                return false;
            }).count();
            List<Integer> list = Lists.newArrayList();
            list.add(oneLevel.intValue());
            list.add(totalSize - oneLevel.intValue());
            dtoList.add(new AlarmEchartDto(entry.getKey(), list));
        }
        dtoList.sort(Comparator.comparing(AlarmEchartDto::getLocalDateTime));
        return ResultBean.success(dtoList);
    }

    @Override
    public void handle(List<MonitorPointData> dataList,Map<String, MhAlarmLimitConfig> configMap,Map<String,Map<Integer,String>> levelMaps,
                       BaseConfig switchConfig,Map<String, RiskEvaluationControl> dyContMap) {
        //优化
        if (!CollectionUtils.isEmpty(dataList)){
            List<MhAlarmSetting> settings = mhAlarmSettingDao.findByAlarmFlag(0);
            //分批处理
            List<List<MonitorPointData>> paList = Lists.partition(dataList,1000);
            for (List<MonitorPointData> list : paList){
                List<MhMonitoringPoint> cachePoints = Lists.newArrayList();
                Map<String,MhMonitoringPoint> cachePointMap = new HashMap<>();
                for (MonitorPointData pointData : list){
                    Long tenentId = pointData.getTenentId();
                    String orgCode = pointData.getOrgCode();
                    String pointCode = pointData.getPointCode();

                    MhMonitoringPoint point = new MhMonitoringPoint();
                    point.setTenentId(tenentId);
                    point.setOrgCode(orgCode);
                    point.setPointCode(pointCode);
                    String key = mhMonitoringPointService.getKeyFromData(point);
                    MhMonitoringPoint cachePoint = mhMonitoringPointService.get(key);
                    if (cachePoint == null) {
                        continue;
                    }
                    cachePoints.add(cachePoint);
                    cachePointMap.put(key,cachePoint);
                }
                List<Long> pointIds = cachePoints.stream().map(MhMonitoringPoint::getId).collect(Collectors.toList());
                List<MhAlarmMessage> msgList = messageDao.selectLastAlarmMessages(pointIds);
                Map<Long, MhAlarmMessage> msgMap = CollectionUtil.isNotEmpty(msgList) ?
                        msgList.stream().filter(m -> m.getMhMonitoringPoint() != null).collect(Collectors.toMap(m -> m.getMhMonitoringPoint().getId(), m -> m))
                        : new HashMap<>();

                List<MhAlarmRecord> records = mhAlarmRecordService.findValidRecords(pointIds,AlarmRecordStateEnum.YES.getValue());
                Map<Long,MhAlarmRecord> recordMap = CollectionUtil.isNotEmpty(records) ?
                        records.stream().filter(m -> m.getMonitoringPointId() != null).collect(Collectors.toMap(MhAlarmRecord::getMonitoringPointId, m -> m))
                        : new HashMap<>();

                List<MhAlarmMessage> normalMessages = new ArrayList<>();
                List<MhAlarmMessage> alarmMessages = new ArrayList<>();
                List<MhAlarmRecord> saveRecords = new ArrayList<>();
                List<MhAlarmRecord> updateRecords = new ArrayList<>();

                list.forEach(each -> {
                    try {
                        handlePointData(each,cachePointMap,msgMap,configMap,normalMessages,alarmMessages,levelMaps,recordMap,
                                saveRecords,updateRecords,switchConfig,settings);
                    } catch (Throwable throwable) {
                        log.error("DefaultIMonitorPointDataHandler error,data:{} ", JSONUtil.toJsonStr(each), throwable);
                    }
                });
                try {
                    //批量保存
                    messageDao.saveAll(normalMessages);
                    if (!CollectionUtils.isEmpty(saveRecords)){
                        mhAlarmRecordService.saveBatch(saveRecords);
                    }
                    if (!CollectionUtils.isEmpty(updateRecords)){
                        mhAlarmRecordService.updateBatchById(updateRecords);
                    }
                    if (!CollectionUtils.isEmpty(alarmMessages)){
                        messageDao.saveAll(alarmMessages);
                        //向webSocket推送报警信息,增加监测点编号
                        monitorPointDataWebSocketService.getPointAlarmMessage(alarmMessages, "ADD");

                        Map<String,List<MhAlarmMessage>> alarmMap = alarmMessages.stream().collect(Collectors.groupingBy(e -> e.getTenentId() + "_" + e.getOrgCode()));
                        for (String key : alarmMap.keySet()){
                            RiskEvaluationControl dyCont = dyContMap.get(key);
                            if (dyCont != null && dyCont.getSwitchState().intValue() == 1) {
                                saveRiskDynamicRecord(alarmMap.get(key), dyCont.getOrgCode(), dyCont.getTenentId());
                            } else {
                                log.info("动态风险-重大危险源报警,动态开关-关闭");
                            }
                        }
                        executor.execute(()->{
                            alarmMessages.forEach(newMsg->{
                                //推送声光报警器调用中间件
                                customAlarmMessageService.send(newMsg, 1);
                            });
                        });

                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
        }
        /*  注解申华上报市平台的代码功能

        BaseConfig isRestConfig = baseConfigService.getBaseConfigFromRedis(SyncConstants.MH_MONITPOINT_API_REST_OPEN);
        boolean isRest = isRestConfig == null ? false : "true".equalsIgnoreCase(isRestConfig.getValue());
        log.debug("... mh sender rest: mh.monitPoint.http.api.open=" + isRest);
        if (isRest) {
            mhMonitPointRestSender.sendMessage(dataList);
        }
        BaseConfig isSocketConfig = baseConfigService.getBaseConfigFromRedis(SyncConstants.MH_MONITPOINT_API_SOCKET_OPEN);
        boolean isSocket = isRestConfig == null ? false : "true".equalsIgnoreCase(isSocketConfig.getValue());
        log.debug("... mh sender socket: mh.monitPoint.ws.open=" + isSocket);
        if (isSocket) {
            mhMonitPointSocketMessageSender.sendMessage(dataList);
        }
        */

        //web大屏监测点数据websocket推送
        executor.execute(() -> monitorPointRealTimeDataPush(dataList));

    }

    /**
     * 目前只显示有毒，可燃气体
     * 需要补全未连接的监测点
     */
    private void monitorPointRealTimeDataPush(List<MonitorPointData> list) {
        MonitorPointData pointData = list.get(0);
        List<MonitorPointWebSocketData> realTimeDataList = convertWebSocketData(list);
        List<Long> realTimeDataIdList = realTimeDataList.stream().map(r -> r.getPointId()).distinct().collect(Collectors.toList());
        List<MonitorPointWebSocketData> pointList = getAllOtherYouDuKeRanPoint(pointData, realTimeDataIdList);
        realTimeDataList.addAll(pointList);
        MonitorPointDataWebSocket.sendInfo(realTimeDataList, WebsocketDataType.POINT_REALTIME_DATA.getIndex());
    }

    private List<MonitorPointWebSocketData> getAllOtherYouDuKeRanPoint(MonitorPointData pointData, List<Long> realTimeDataIdList) {
        Long tenentId = pointData.getTenentId();
        String orgCode = pointData.getOrgCode().substring(0, 7);
        //获取当前公司所有未连接监测点
        List<MhMonitoringPoint> pointList = monitoringPointDao.findAllYouDuKeRanPoint(tenentId, orgCode);
        pointList = pointList.stream().filter(r -> !realTimeDataIdList.contains(r.getId())).collect(Collectors.toList());
        List<MonitorPointWebSocketData> resultList = new ArrayList<>(pointList.size());
        for (MhMonitoringPoint point : pointList) {
            MonitorPointWebSocketData webSocketData = new MonitorPointWebSocketData();
            BeanUtils.copyProperties(point, webSocketData);
            webSocketData.setValueResult("--");
            MhMonitoringType mhMonitoringType = point.getMhMonitoringType();
            webSocketData.setType(mhMonitoringType != null ? mhMonitoringType.getName() : "");
            webSocketData.setTypeCode(mhMonitoringType != null ? mhMonitoringType.getCode() : "");
            resultList.add(webSocketData);
        }
        return resultList;
    }


    @Override
    public void te() {
        for (int i = 0; i < 3000; i++) {
            MhAlarmMessage newMsg = new MhAlarmMessage();
            newMsg.setState(0);
            newMsg.setAlarmTime(LocalDateTime.now());
            newMsg.setDetail("测试数据{" + i + "}");
            newMsg.setLevel(2);
            newMsg.setValue(String.valueOf(i));
            newMsg.setMhMonitoringPoint(monitoringPointDao.findById(1309L).get());
            newMsg.setMhMonitoringType(mhMonitoringTypeDao.findById(51L).get());
            MhAlarmMessage save = messageDao.save(newMsg);
        }
    }

    /**
     * 保存设备报警配置
     *
     * @param beans
     */
    @Override
    public void saveAlarmSetting(List<MhAlarmSettingBean> beans) {
        if (!CollectionUtils.isEmpty(beans)) {
            for (MhAlarmSettingBean bean : beans) {
                if (bean.getId() != null) {
                    MhAlarmSetting ms = mhAlarmSettingDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("配置不存在"));
                    ms.setAlarmFlag(bean.getAlarmFlag());
                    mhAlarmSettingDao.save(ms);
                }
            }
        }
    }

    /**
     * 查看报警配置列表
     *
     * @return
     */
    @Override
    public List<MhAlarmSettingBean> getAlarmSettings() {
        List<MhAlarmSettingBean> beans = new ArrayList<>();
        List<MhAlarmSetting> all = mhAlarmSettingDao.findAll();
        if (!CollectionUtils.isEmpty(all)) {
            for (MhAlarmSetting ms : all) {
                MhAlarmSettingBean bean = new MhAlarmSettingBean();
                BeanUtils.copyProperties(ms, bean);
                beans.add(bean);
            }
        }
        return beans;
    }


    private List<MonitorPointWebSocketData> convertWebSocketData(List<MonitorPointData> list) {
        //添加监测点信息
        List<MonitorPointWebSocketData> resultList = new ArrayList<>(list.size());
        for (MonitorPointData pointData : list) {
            MhMonitoringPoint point = new MhMonitoringPoint();
            point.setTenentId(pointData.getTenentId());
            point.setOrgCode(pointData.getOrgCode());
            point.setPointCode(pointData.getPointCode());
            String key = mhMonitoringPointService.getKeyFromData(point);
            point = mhMonitoringPointService.get(key);
            if (point == null) {
                continue;
            } else {
                //暂时只有有毒可燃气体两种监测点，暂时无需设备id
//                BpMonitoringPointRel pointRel = bpMonitoringPointRelDao.findFirstByMonitoringPointId(point.getId());
//                if (pointRel == null) {
//                    continue;
//                }
                //只取有毒可燃气体
                MhMonitoringType mhMonitoringType = point.getMhMonitoringType();
                if (mhMonitoringType == null || mhMonitoringType.getCategoryId() == null || mhMonitoringType.getCategoryId() == 0) {
                    continue;
                }
                MonitorPointWebSocketData webSocketData = new MonitorPointWebSocketData();
                BeanUtils.copyProperties(pointData, webSocketData);
                webSocketData.setUnit(point.getUnit());
                webSocketData.setPointId(point.getId());
                webSocketData.setType(mhMonitoringType != null ? mhMonitoringType.getName() : "");
                webSocketData.setName(point.getName());
                webSocketData.setLocation(point.getLocation());
                webSocketData.setTypeCode(mhMonitoringType.getCode());
                //监测点关闭显示"--"
                if (point.getState() == null || point.getState() == 0) {
                    webSocketData.setValueResult("--");
                } else {
                    webSocketData.setValueResult(mhMonitoringRealTimeService.getVauleByPointsUnits(point, String.valueOf(pointData.getValue())));
                }
                resultList.add(webSocketData);
            }
        }
        return resultList;
    }


    private MhMonitoringPoint handlePointData(MonitorPointData pointData,Map<String,MhMonitoringPoint> cachePointMap,Map<Long, MhAlarmMessage> msgMap,
                                              Map<String,MhAlarmLimitConfig> configMap,List<MhAlarmMessage> normalMessages,List<MhAlarmMessage> alarmMessages,Map<String,Map<Integer,String>> levelMaps,
                                              Map<Long,MhAlarmRecord> recordMap,List<MhAlarmRecord> saveRecords,List<MhAlarmRecord> updateRecords,
                                              BaseConfig switchConfig,List<MhAlarmSetting> settings) {
        Long tenentId = pointData.getTenentId();
        String orgCode = pointData.getOrgCode();
        String pointCode = pointData.getPointCode();

        MhMonitoringPoint point = new MhMonitoringPoint();
        point.setTenentId(tenentId);
        point.setOrgCode(orgCode);
        point.setPointCode(pointCode);
        String key = mhMonitoringPointService.getKeyFromData(point);
        MhMonitoringPoint cachePoint = cachePointMap.get(key);
        log.debug(key);
        if (cachePoint == null) {
            return null;
        }
        log.debug("find monitorPoint:id={},code={},state={}", cachePoint.getId(), cachePoint.getPointCode(),
                cachePoint.getState());

        boolean alarm = false;
        int alarmLevel = -1;
        double val = pointData.getValue();
        double limitVal = -1;
        // 液位高高位
        Double highValue2 = null;
        // 液位高位
        Double highValue1 = null;
        // 液位低位
        Double lowValue1 = null;
        // 液位低低位
        Double lowValue2 = null;

        if (StringUtils.isNotBlank(cachePoint.getLowValue1())) {
            lowValue1 = Double.valueOf(cachePoint.getLowValue1());
        }

        if (StringUtils.isNotBlank(cachePoint.getLowValue2())) {
            lowValue2 = Double.valueOf(cachePoint.getLowValue2());
        }
        if (StringUtils.isNotBlank(cachePoint.getHighValue1())) {
            highValue1 = Double.valueOf(cachePoint.getHighValue1());
        }
        if (StringUtils.isNotBlank(cachePoint.getHighValue2())) {
            highValue2 = Double.valueOf(cachePoint.getHighValue2());
        }
        // 一级低报
        if (lowValue1 != null && lowValue2 != null
                && val > lowValue2 && val <= lowValue1) {
            alarm = true;
            alarmLevel = 1;
            limitVal = lowValue1;
        }
        // 一级高报
        if (highValue1 != null && highValue2 != null
                && val < highValue2 && val >= highValue1) {
            alarm = true;
            alarmLevel = 2;
            limitVal = highValue1;
        }
        // 二级低报
        if (lowValue2 != null && val <= lowValue2) {
            alarm = true;
            alarmLevel = 3;
            limitVal = lowValue2;
        }
        // 二级高报
        if (cachePoint.getHighValue2() != null && val >= highValue2) {
            alarm = true;
            alarmLevel = 4;
            limitVal = highValue2;
        }

        checkAlarm(cachePoint, alarm, alarmLevel, val, limitVal, msgMap,configMap,normalMessages,alarmMessages,levelMaps,recordMap,saveRecords,
                updateRecords,switchConfig,settings);
        return cachePoint;
    }

    private void checkAlarm(MhMonitoringPoint cachePoint, boolean alarm, int alarmLevel, double val, double limitVal, Map<Long, MhAlarmMessage> msgMap,
                            Map<String,MhAlarmLimitConfig> configMap,List<MhAlarmMessage> normalMessages,List<MhAlarmMessage> alarmMessages,Map<String,Map<Integer,String>> levelMaps,
                            Map<Long,MhAlarmRecord> recordMap,List<MhAlarmRecord> saveRecords,List<MhAlarmRecord> updateRecords,
                            BaseConfig switchConfig,List<MhAlarmSetting> settings) {
        Long pointId = cachePoint.getId();
        MhAlarmMessage msg = msgMap.get(pointId);
        log.debug("pointId={},pointCode={},alarm={},state={},msg={},msg.state={}", cachePoint.getId(),
                cachePoint.getPointCode(), alarm + "",
                (cachePoint.getState() != null && cachePoint.getState() == 1) + "", msg != null,
                msg != null ? msg.getState() : -1);
        MhAlarmLimitConfig config = configMap.get(cachePoint.getTenentId()+"_"+cachePoint.getOrgCode());
        //新报警逻辑（分级报警）
//        log.info("执行新报警逻辑,监测点ID： {}", cachePoint.getId());
        if (switchConfig != null && "1".equals(switchConfig.getValue())){
            if (alarm && (cachePoint.getState() != null && cachePoint.getState() == 1)
                    && (msg == null || msg.getState() > 0 )){
                newAlarmMessage2(cachePoint, alarmLevel, val, limitVal,config,levelMaps,recordMap,saveRecords,updateRecords,switchConfig,normalMessages,settings);
            }
            return;
        }

        // 判断产生新的报警
        if (alarm && (cachePoint.getState() != null && cachePoint.getState() == 1)
                && (msg == null || msg.getState() > 0 || msg.getLevel() != alarmLevel) && !isRepeatAlarm(alarmLevel, msg)) {
            newAlarmMessage(cachePoint, alarmLevel, val, limitVal, normalMessages,alarmMessages,settings);
        }
        // 没有报警，但是如果原来正在报警需要把它设置为已经恢复
        if (!alarm && msg != null && msg.getState() == 0) {
            msg.setState(1);
//                messageDao.save(msg);
            normalMessages.add(msg);
//                log.info("alarm message restore msg id {}", msg.getId());
        }
    }

    /**
     * 报警等级减小 配置时间内 判断为重复的报警
     *
     * @param alarmLevel
     * @return
     */
    boolean isRepeatAlarm(int alarmLevel, MhAlarmMessage lastAlarm) {
        if (lastAlarm == null) {
            return false;
        }
        if (lastAlarm.getState() != 0){
            return false;
        }
        return isAlarmReduce(lastAlarm.getLevel(), alarmLevel);
    }

    /**
     * 报警等级减小(或报警等级相同)：4->2 3->1
     *
     * @param lastLever 上次报警等级
     * @param currLever 本次报警等级
     * @return
     */
    boolean isAlarmReduce(Integer lastLever, Integer currLever) {
        return (lastLever == 4 && currLever == 2) || (lastLever == 3 && currLever == 1) || lastLever.equals(currLever);
    }

    private void newAlarmMessage(MhMonitoringPoint cachePoint, int alarmLevel, double val, double limitVal,List<MhAlarmMessage> normalMessages,List<MhAlarmMessage> alarmMessages,List<MhAlarmSetting> settings) {
        MhAlarmMessage newMsg = new MhAlarmMessage();
        //newMsg.setCode(bizCodeGeneratorFacade.weiXianYuanBaoJing(cachePoint.getTenentId(), cachePoint.getOrgCode()));
        newMsg.setTenentId(cachePoint.getTenentId());
        newMsg.setOrgCode(cachePoint.getOrgCode());
        newMsg.setAlarmTime(LocalDateTime.now());
        newMsg.setDetail(formatMsg(cachePoint, val, limitVal, alarmLevel));
        newMsg.setLevel(alarmLevel);
        newMsg.setValue(val + StringUtil.escapeNull(cachePoint.getMhMonitoringType().getUnit()));
        newMsg.setMhMonitoringPoint(cachePoint);
        newMsg.setMhMonitoringType(cachePoint.getMhMonitoringType());
        completePositionAndMhInfo(newMsg, cachePoint);
        //2.3根据设备报警配置 报警是否自动处理
        if (checkPointAlarmSetting(cachePoint, newMsg,settings)) {
            newMsg.setState(2);
            newMsg.setRemark("自动忽略");
            normalMessages.add(newMsg);
        } else {
            newMsg.setState(0);
            alarmMessages.add(newMsg);
        }
    }

    private void newAlarmMessage2(MhMonitoringPoint cachePoint, int alarmLevel, double val, double limitVal,MhAlarmLimitConfig config,Map<String,Map<Integer,String>> levelMaps,
                                  Map<Long,MhAlarmRecord> recordMap,List<MhAlarmRecord> saveRecords,List<MhAlarmRecord> updateRecords,
                                  BaseConfig switchConfig,List<MhAlarmMessage> normalMessages,List<MhAlarmSetting> settings) {
        MhAlarmMessage newMsg = new MhAlarmMessage();
        newMsg.setTenentId(cachePoint.getTenentId());
        newMsg.setOrgCode(cachePoint.getOrgCode());
        newMsg.setAlarmTime(LocalDateTime.now());
        newMsg.setDetail(formatMsg(cachePoint, val, limitVal, alarmLevel));
        newMsg.setLevel(alarmLevel);
        newMsg.setValue(val + StringUtil.escapeNull(cachePoint.getMhMonitoringType().getUnit()));
        newMsg.setMhMonitoringPoint(cachePoint);
        newMsg.setMhMonitoringType(cachePoint.getMhMonitoringType());
        completePositionAndMhInfo(newMsg, cachePoint);
        //2.3根据设备报警配置 报警是否自动处理
        if (checkPointAlarmSetting(cachePoint, newMsg,settings)) {
            newMsg.setState(2);
            newMsg.setRemark("自动忽略");
            normalMessages.add(newMsg);
        } else {
            newMsg.setState(0);
            synchronized (("monitoring_point_id_"+newMsg.getMhMonitoringPoint().getId()).intern()){
                generateAlarm(newMsg,config,levelMaps,recordMap,saveRecords,updateRecords,switchConfig);
            }
        }
    }

    @Override
    public void test(Long id){
        MhAlarmLimitConfig config = mhAlarmLimitConfigService.findOneConfig(1L,"001-001");
//        generateAlarm(messageDao.getOne(id),config);
//        List<MhAlarmMessage> mhList = new ArrayList<>();
//        MhAlarmMessage one = messageDao.findById(id).orElse(null);
//        if (one != null && one.getState() != null && one.getState() != 2) {
//            one.setState(2);
//            one.setRemark("流程同步处理");
//            one.setHandleTime(LocalDateTime.now());
//            one.setAlarmReason("流程同步处理");
//            mhList.add(one);
//        }
//        monitoringCenterService.handlingHazardAlarms(mhList);
    }

//    @Override
    public void generateAlarm(MhAlarmMessage message,MhAlarmLimitConfig config,Map<String,Map<Integer,String>> levelMaps,Map<Long,MhAlarmRecord> recordMap,
                              List<MhAlarmRecord> saveRecords,List<MhAlarmRecord> updateRecords,BaseConfig switchConfig){
        //分级报警新逻辑
        Map<Integer,String> levelMap = levelMaps.get(message.getTenentId()+"_"+message.getOrgCode());
        MhAlarmRecord record = recordMap.get(message.getMhMonitoringPoint().getId());
        if (record == null){
            //产生新的记录
            record = new MhAlarmRecord();
            record.setMonitoringPointId(message.getMhMonitoringPoint().getId());
            record.setTenentId(message.getTenentId());
            record.setOrgCode(message.getOrgCode());
            doNewAlarmRecord(record,message,config,levelMap);
//            mhAlarmRecordService.save(record);
            saveRecords.add(record);
            boolean validFlag = isValid(config,record.getStartTime());
            if (validFlag){
                if (config.getExceedTimes() <= record.getExceedCount()){
                    checkIsAlarm(record,message,config,levelMap,switchConfig,updateRecords);
                }
            }
            return;
        }
        boolean validFlag = isValid(config,record.getStartTime());
        if (!validFlag){
            //非有效期内，如果没触发单据则重新开始，若已触发单据则不处理
            if (StringUtils.isBlank(record.getAlarmCode())){
                doNewAlarmRecord(record,message,config,levelMap);
//                mhAlarmRecordService.updateById(record);
                updateRecords.add(record);
            }
            return;
        }
        //有效周期之内
        //是否超限
        if (config.getExceedTimes() <= record.getExceedCount() +1){
            checkIsAlarm(record,message,config,levelMap,switchConfig,updateRecords);
        }else {
            //没有超限，仅更新record
            //如果已生成单据
            if (StringUtils.isNotBlank(record.getAlarmCode())){
                //判断是否超过当前单据最高等级
//                    doAlarmUpdate(record,save,config,false);
            }else {
                record.setExceedCount(record.getExceedCount() + 1);
                //判断是否比当前报警等级高
                setAlarmLevel(record,message,config,levelMap);
//                mhAlarmRecordService.updateById(record);
                updateRecords.add(record);
            }
        }
    }

    private void checkIsAlarm(MhAlarmRecord record,MhAlarmMessage message,MhAlarmLimitConfig config,Map<Integer,String> levelMap,
                              BaseConfig switchConfig,List<MhAlarmRecord> updateRecords){
        if (StringUtils.isBlank(record.getAlarmCode())){
            MhAlarmMessage save = messageDao.save(message);
            log.info("new alarm message point code {} id {}", message.getMhMonitoringPoint().getPointCode(), message.getId());
            //向webSocket推送报警信息,增加监测点编号
            monitorPointDataWebSocketService.getPointAlarmMessage(Lists.newArrayList(save), "ADD");
            //动态风险
            RiskEvaluationControl dyCont = riskEvaluationControlDao.findByNameAndOrgCodeAndTenentId("动态安全风险评估", save.getOrgCode().substring(0, 7), save.getTenentId());
            if (dyCont != null && dyCont.getSwitchState().intValue() == 1) {
                saveRiskDynamicRecord(Lists.newArrayList(save), save.getOrgCode(), save.getTenentId());
            } else {
                log.info("动态风险-重大危险源报警id{},动态开关-关闭", save.getId());
            }
            //推送声光报警器调用中间件
            customAlarmMessageService.send(save, 1);
            //第一次生成单据
            record.setExceedCount(record.getExceedCount() + 1);
            record.setAlarmMessageId(save.getId());
            record.setDetail(save.getDetail());
            //判断是否比当前报警等级高
            setAlarmLevel(record,save,config,levelMap);

            if (switchConfig != null && "1".equals(switchConfig.getValue())) {
                //生成报警单据并返回单据
                String alarmCode = doAlarm(save,record);
                if (StringUtils.isNotBlank(alarmCode)){
                    record.setExceedCount(0);
                    record.setAlarmCode(alarmCode);
                    record.setChangeTime(LocalDateTime.now());
                    record.setCodeLevelName(record.getMaxLevelName());

                    save.setDetail(record.getMaxDetail());
                    save.setLevel(record.getMaxLevel());
                    save.setValue(record.getMaxValue());
                    messageDao.save(save);
                }
            }
//            mhAlarmRecordService.updateById(record);
            updateRecords.add(record);
        }else {
            //已生成单据,需更新单据(不要了)
//                    doAlarmUpdate(record,save,config,true);
        }
    }

    private void setAlarmLevel(MhAlarmRecord record, MhAlarmMessage save, MhAlarmLimitConfig config,Map<Integer,String> levelMap){
        //判断是否比当前报警等级高
        if (save.getLevel() >= record.getMaxLevel()){
            record.setMaxLevelName(levelMap.get(save.getLevel()));
            record.setMaxLevel(save.getLevel());
            record.setMaxValue(save.getValue());
            record.setMaxDetail(save.getDetail());
        }
        record.setDetail(save.getDetail());
        record.setLevelName(levelMap.get(save.getLevel()));
        record.setUpdateCount(record.getUpdateCount()+1);
        setAlarmRecord(record, save, config);
    }

    private void doNewAlarmRecord(MhAlarmRecord record, MhAlarmMessage save, MhAlarmLimitConfig config,Map<Integer,String> levelMap){
        record.setStartTime(LocalDateTime.now());
        record.setLevelName(levelMap.get(save.getLevel()));
        record.setMaxLevelName(levelMap.get(save.getLevel()));
        Integer updateCount = record.getUpdateCount();
        record.setUpdateCount(updateCount != null ? updateCount+1 : 1);
        record.setExceedCount(1);
        record.setDetail(save.getDetail());
        record.setMaxLevel(save.getLevel());
        record.setMaxDetail(save.getDetail());
        record.setMaxValue(save.getValue());
        record.setChangeTime(record.getStartTime());
        setAlarmRecord(record, save, config);
        record.setState(AlarmRecordStateEnum.YES.getValue());
    }

    private void doAlarmUpdate(MhAlarmRecord record, MhAlarmMessage save, MhAlarmLimitConfig config,boolean limitFlag){
        //判断是否超过当前单据最高等级
        if (record.getCodeLevelName().equals(BaseConfigCodes.MH_GRADING_ALARM_BLUE)){
            if (save.getLevel() > record.getMaxLevel() && save.getLevel() > BaseConfigCodes.MH_HIGH_ALARM){
                record.setExceedCount(record.getExceedCount() + 1);
                record.setUpdateCount(record.getUpdateCount()+1);
                record.setMaxLevelName(BaseConfigCodes.MH_GRADING_ALARM_YELLOW);
                record.setLevelName(BaseConfigCodes.MH_GRADING_ALARM_YELLOW);
                record.setMaxLevel(save.getLevel());
                setAlarmRecord(record, save, config);
                mhAlarmRecordService.updateById(record);
                //更新单据（需流程引擎接口支持）
                //TODO
                if (limitFlag){

                }
            }
        }
    }

    private void setAlarmRecord(MhAlarmRecord record, MhAlarmMessage save, MhAlarmLimitConfig config){
        record.setLastTime(save.getAlarmTime());
        record.setAlarmLevel(save.getLevel());
        record.setValue(save.getValue());
        record.setAlarmRule("每个循环的"+config.getCheckRateDescribe()+config.getPeriodUnit()+"内达到"+config.getExceedTimes()+"次超限，则按这个期间的最高超限报警等级发生首次报警。");
    }

    private String doAlarm(MhAlarmMessage message,MhAlarmRecord record){
        MhGradingAlarmDto mhGradingAlarmDto = new MhGradingAlarmDto();
        mhGradingAlarmDto.setAlarmLevel(record.getMaxLevelName());
        mhGradingAlarmDto.setAlarmContent(record.getMaxDetail());
        mhGradingAlarmDto.setAlarmValue(record.getMaxValue());
        mhGradingAlarmDto.setTenentId(message.getTenentId());
        mhGradingAlarmDto.setOrgCode(message.getOrgCode());
        mhGradingAlarmDto.setMonitoringPointName(message.getMhMonitoringPoint().getName());
        mhGradingAlarmDto.setPointDept(message.getMhMonitoringPoint().getResponsibleDept());
        mhGradingAlarmDto.setId(message.getId());
        return mhGradingAlarmService.httpUrlGradingAlarmPush(mhGradingAlarmDto);
    }

    private boolean isValid(MhAlarmLimitConfig config,LocalDateTime startTime){
        boolean flag = false;
        LocalDateTime dateTime = LocalDateTime.now();
        PeriodUnitEnum periodUnit = PeriodUnitEnum.find(config.getPeriodUnit());
        switch (periodUnit) {
            case MONTH:
                flag = startTime.plusMonths(config.getCheckRateDescribe().longValue()).isAfter(dateTime);
                break;
            case MINUTE:
                flag = startTime.plusMinutes(config.getCheckRateDescribe().longValue()).isAfter(dateTime);
                break;
            case DAY:
                flag = startTime.plusDays(config.getCheckRateDescribe().longValue()).isAfter(dateTime);
                break;
            case HOUR:
                flag = startTime.plusHours(config.getCheckRateDescribe().longValue()).isAfter(dateTime);
                break;
            case WEEK:
                flag = startTime.plusWeeks(config.getCheckRateDescribe().longValue()).isAfter(dateTime);
                break;
            default:
        }
        return flag;
    }

    @Override
    public void saveRiskDynamicRecord(List<MhAlarmMessage> messages, String orgCode, Long tenentId) {
        if (CollectionUtils.isEmpty(messages)) {
            return;
        }
        List<RiskDynamicRecord> batchRecords = new ArrayList<>();
        Map<Integer, List<MhAlarmMessage>> levelMap = messages.stream().collect(Collectors.groupingBy(MhAlarmMessage::getLevel));
        for (Map.Entry<Integer, List<MhAlarmMessage>> entry : levelMap.entrySet()) {
            String param = "";
            if (entry.getKey() == 1 || entry.getKey() == 2) {
                param = "设备监测点一级报警";
            } else {
                param = "设备监测点二级报警";
            }
            RiskDynamicConfig config = riskDynamicConfigDao.getMhPointConfigByEnableFlagAndParam(1, param, tenentId, orgCode);
            for (MhAlarmMessage message : entry.getValue()) {
                batchRecords = convertRiskDynamicConfigs(message, config, batchRecords);

            }
        }
        if (!CollectionUtils.isEmpty(batchRecords)) {
            riskDynamicRecordService.saveOrUpdateBatch(batchRecords);
            riskEvaluationBusinessService.editDynamicDistrictLevel(batchRecords, "重大危险源报警");
        }
    }

    private List<RiskDynamicRecord> convertRiskDynamicConfigs(MhAlarmMessage message, RiskDynamicConfig config, List<RiskDynamicRecord> batchRecords) {
        List<RiskDistrict> districtList = riskDistrictDao.findAll();
        MhMonitoringPoint mhMonitoringPoint = message.getMhMonitoringPoint();
        Date date = new Date();
        if (mhMonitoringPoint != null) {
            MonitorWebSocketPointAlarmData alarmData = monitorPointDataWebSocketService.covertPointAlarmData(mhMonitoringPoint, new MonitorWebSocketPointAlarmData(), message);
            //过滤库房
            if (alarmData.getDeviceTypeName() != null && alarmData.getDeviceTypeName().equals("库房")) {
                return batchRecords;
            }
            if (alarmData.getLocationType() != null && StringUtils.isNotBlank(alarmData.getLocation()) && config != null && !CollectionUtils.isEmpty(districtList)) {
                for (RiskDistrict district : districtList) {
                    RiskDynamicRecord eRecord = null;
                    if (alarmData.getLocationType().intValue() == 0) {
                        eRecord = getEligiblePointRecord(district, message, alarmData, config, date);
                    } else {
                        eRecord = getEligiblePolygonRecord(district, message, alarmData, config, date);
                    }
                    if (eRecord != null) {
                        batchRecords.add(eRecord);
                    }
                }
            }
        }
        return batchRecords;
    }

    private RiskDynamicRecord getEligiblePolygonRecord(RiskDistrict district, MhAlarmMessage message, MonitorWebSocketPointAlarmData alarmData, RiskDynamicConfig config, Date date) {
        RiskDynamicRecord record = new RiskDynamicRecord();
        if (StringUtils.isBlank(district.getCoordinates())) {
            return null;
        }
        MapUtils.SafetyPoints dPoints = MapUtils.parse3DSafetyPointsFromJson(alarmData.getLocation());
        MapUtils.SafetyPoints rPoints = MapUtils.parse3DSafetyPointsFromJson(district.getCoordinates());
        if (rPoints == null || CollectionUtils.isEmpty(rPoints.getPoints())) {
            return null;
        }
        //区域点位
        Coordinate[] districtCoordinates = workFlowTaskDynamicService.getCoordinate(rPoints.getPoints());
        Coordinate[] dataCoordinates = workFlowTaskDynamicService.getCoordinate(dPoints.getPoints());
        try {
            GeometryFactory gf = new GeometryFactory();
            Geometry taskGeometry = gf.createPolygon(dataCoordinates);
            Geometry areaGeometry = gf.createPolygon(districtCoordinates);
            //放入有公共点的区域
            if (taskGeometry.intersects(areaGeometry)) {
                record.setRiskDistrictId(district.getId());
                record.setRiskType(0);
                record.setTaskCode(message.getId().toString());
                record.setDynamicConfigId(config.getId());
                record.setScore(config.getScore());
                record.setStatus(0);
                record.setCreateTime(date);
                record.setUpdateTime(date);
                record.setTenentId(message.getTenentId());
                record.setOrgCode(message.getOrgCode());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
        return record;
    }

    private RiskDynamicRecord getEligiblePointRecord(RiskDistrict district, MhAlarmMessage message, MonitorWebSocketPointAlarmData alarmData, RiskDynamicConfig config, Date date) {
        RiskDynamicRecord record = new RiskDynamicRecord();
        if (StringUtils.isBlank(district.getCoordinates())) {
            return null;
        }
        //区域点位
        MapUtils.SafetyPoints districtPoints = MapUtils.parse3DSafetyPointsFromJson(district.getCoordinates());
        Double[] pointLons = new Double[districtPoints.getPoints().size()];
        Double[] pointLats = new Double[districtPoints.getPoints().size()];
        MapUtils.getCoordinateArr(districtPoints.getPoints(), pointLons, pointLats);
        //报警点位
        MapUtils.WwytPoint alarmPoint = MapUtils.parseSinglePoint(alarmData.getLocation());
        //判断改点是在区域内
        if (RegionUtil.isInPolygon(alarmPoint.getX(), alarmPoint.getY(), pointLons, pointLats)) {
            record.setRiskDistrictId(district.getId());
            record.setRiskType(0);
            record.setTaskCode(message.getId().toString());
            record.setDynamicConfigId(config.getId());
            record.setScore(config.getScore());
            record.setStatus(0);
            record.setCreateTime(date);
            record.setUpdateTime(date);
            record.setTenentId(message.getTenentId());
            record.setOrgCode(message.getOrgCode());
        }
        return record;
    }

    private boolean checkPointAlarmSetting(MhMonitoringPoint cachePoint, MhAlarmMessage newMsg,List<MhAlarmSetting> settings) {
        //根据配置判断是否报警
        BpDeviceFacilityCollection collection = bpDeviceFacilityCollectionDao.getDeviceTypeByPointId(cachePoint.getId());
        if (collection != null && collection.getDeviceTypeName() != null && collection.getDeviceTypeName().equals("生产装置")) {
            //设备信息
            Optional<BpProductionFacility> obf = bpProductionFacilityDao.findById(collection.getDeviceId());
            if (obf.isPresent()) {
                BpProductionFacility facility = obf.get();
                int r = bpDeviceFacilityRepairRecordDao.countByDeviceFacilityIdAndNowDate(facility.getId(), new Date());
                int m = bpDeviceFacilityMaintainRecordDao.countByDeviceFacilityIdAndNowDate(facility.getId(), new Date());
                //将配置中 是否报警为'否'的配置都查出来
                if (!CollectionUtils.isEmpty(settings)) {
                    for (MhAlarmSetting setting : settings) {
                        if (setting.getName().equals("停用")) {
                            if (facility.getState() != null && facility.getState().equals(ProductionFacilityStates.STOPED.getId())) {
                                newMsg.setAlarmReason("设备已停用");
                                return true;
                            }
                        } else if (setting.getName().equals("报废")) {
                            if (facility.getLifecycle() != null && facility.getLifecycle().equals(DeviceFacilityLifecycles.SCRAPED.getId())) {
                                newMsg.setAlarmReason("设备已报废");
                                return true;
                            }
                        } else if (setting.getName().equals("维修")) {
                            if (r > 0) {
                                newMsg.setAlarmReason("设备维修中");
                                return true;
                            }

                        } else if (setting.getName().equals("保养")) {
                            if (m > 0) {
                                newMsg.setAlarmReason("设备保养中");
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    private void completePositionAndMhInfo(MhAlarmMessage newMsg, MhMonitoringPoint cachePoint) {
        BpDeviceFacilityCollection device = bpDeviceFacilityCollectionService
                .findMonitoryPointBindedDevice(cachePoint.getId());
        if (device != null) {
            newMsg.setAlarmPosition(device.getName());
            newMsg.setMajorHazardFlag((byte) (device.getMajorHazardId() != null ? 1 : 0));
            if (device.getMajorHazardId() != null) {
                mhMajorHazardDao.findById(device.getMajorHazardId()).ifPresent((mh) -> {
                    newMsg.setMajorHazardName(mh.getName());
                    // newMsg.setMajorHazardLevel(mh.getLevel());
                });
            }
        }
    }

    private String formatMsg(MhMonitoringPoint cachePoint, double val, double limitVal, int alarmLevel) {
        // String threshHold = "";
        // if (val < cachePoint.getLowValue2()) {
        // threshHold = cachePoint.getLowValue2() + cachePoint.getMhMonitoringType().getUnit();
        // } else if (val < cachePoint.getLowValue1()) {
        // threshHold = cachePoint.getLowValue1() + cachePoint.getMhMonitoringType().getUnit();
        // } else if (val < cachePoint.getHighValue1()) {
        // threshHold = cachePoint.getHighValue1() + cachePoint.getMhMonitoringType().getUnit();
        // } else {
        // threshHold = cachePoint.getHighValue2() + cachePoint.getMhMonitoringType().getUnit();
        // }

        // return String.format("%s超标，阈值%s，当前报警数值%.2f%s", cachePoint.getMhMonitoringType().getName(), limitVal, val,
        // cachePoint.getMhMonitoringType().getUnit());
        String pointCode = cachePoint.getPointCode();
        String alarmName = "";
        switch (alarmLevel) {
            case 1:
                alarmName = "低位限";
                break;
            case 2:
                alarmName = "高位限";
                break;
            case 3:
                alarmName = "低低位限";
                break;
            case 4:
                alarmName = "高高位限";
        }
        return String.format("(位号%s),发生\"%s\"报警，阈值\"%s\",监测值\"%.2f\"", pointCode, alarmName, limitVal, val);
    }

}
